import {WxCheckSession, WxGetUserProfile, WxLogin} from '/src/utils/wechat'
import {getUserInfo, login} from '/src/api/login.js'
import {topCaseToken} from '/src/utils/constant'


const state = {
  token: wx.getStorageSync(topCaseToken),
  wxUserInfo: wx.getStorageSync('wxUserInfo'),
  authorized: false, // 用户是否授权过用户信息
  logging: false, // 登录中,
  loginPromise: undefined,
  loggedListeners: new Map() // 登录成功监听器
}

const mutations = {
  setToken(state, token) {
    wx.setStorageSync(topCaseToken, token)
    state.token = token
  },
  setOpenUserInfo(state, loginUser = {}) {
    if (loginUser.wxuuid) {
      state.authorized = true
    } else {
      state.authorized = false
    }
    wx.setStorageSync('wxUserInfo', loginUser)
    console.info('登录用户信息', loginUser)
    state.wxUserInfo = loginUser
  },
  setLogging(state, logging) {
    state.logging = logging
  },
  addLoggedListener(state, {name, listener}) {
    console.info('添加登录成功监听器：' + name)
    if (listener instanceof Function) {
      state.loggedListeners.set(name, listener)
    } else {
      throw new Error('参数类型错误，请传入回调函数')
    }
  },
  removeLoggedListener(state, name) {
    console.info('移除登录成功监听器：' + name)
    state.loggedListeners.delete(name)
  }
}

const actions = {
  login({commit, dispatch, state}) {
    if (!state.logging) {
      state.loginPromise = new Promise((resolve, reject) => {
        commit('setLogging', true)
        WxLogin().then(function(res) {
          login(res.code).then(function(res2) {
            commit('setLogging', false)
            if (res2.meta.status === 'success') {
              commit('setToken', res2.meta.token)
              const userInfo = res2.body.data
              commit('setOpenUserInfo', userInfo)
              dispatch('updateWxUserInfo')
              resolve(userInfo)
            } else {
              commit('setOpenUserInfo')
              reject(res2)
            }
          }).catch(err => {
            commit('setLogging', false)
            reject(err)
          })
        }).catch(() => {
          commit('setLogging', false)
        })
      })
    }
    return state.loginPromise
  },
  updateWxUserInfo({commit, dispatch, state}) {
    const fun = () => {
      console.info('申请用户授权')
      return WxGetUserProfile().then(function(res) {
        getUserInfo(res.encryptedData, res.iv, res.signature).then(res => {
          commit('setLogging', false)
          if (res.meta.status === 'success') {
            // 登录成功的事件分发
            state.loggedListeners.forEach(f => {
              Promise.resolve().then(f)
            })
            const userInfo = res.body.data
            commit('setOpenUserInfo', userInfo)
            // dispatch('location/authorize', null, {root: true})
            // dispatch('dmsuser/getDmsUser', null, {root: true})
          }
        }).catch(() => {
          commit('setLogging', false)
        })
      }).catch(() => {
        commit('setLogging', false)
        console.info('用户拒绝授权')
      })
    }
    if (!state.logging) {
      commit('setLogging', true)
      // 判断是否需要再次授权
      wx.getSetting().then(res => {
        console.info(res)
      })
      WxCheckSession().then(() => {
        console.info('用户已经授权过，未失效，不用再次申请授权')
        if (!state.authorized) { // 如果后台数据丢失，需要重新获取用户授权信息
          return fun()
        }
      }).catch(() => {
        return fun()
      })
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
